﻿Imports System.Text

Public Class CreateExam

    Private idList As New List(Of Integer)
    Private selectIdList As New List(Of Integer)
    Private judgeIdList As New List(Of Integer)
    Private fillIdList As New List(Of Integer)
    Private type As Integer
    Private selectCount As Integer = 0
    Private judgeCount As Integer = 0
    Private fillCount As Integer = 0
    Private selectScore As Integer = 5
    Private judgeScore As Integer = 5
    Private fillScore As Integer = 5
    Private examIdForUpdate As Integer = 0
    Private selectNewAddedIds As New List(Of Integer)
    Private judgeNewAddedIds As New List(Of Integer)
    Private fillNewAddedIds As New List(Of Integer)
    Private toDeleteIds As New List(Of Integer)
    Public Property IdList1 As List(Of Integer)
        Get
            Return idList
        End Get
        Set(value As List(Of Integer))
            idList = value
        End Set
    End Property

    Public Property SelectIdList1 As List(Of Integer)
        Get
            Return selectIdList
        End Get
        Set(value As List(Of Integer))
            selectIdList = value
        End Set
    End Property

    Public Property JudgeIdList1 As List(Of Integer)
        Get
            Return judgeIdList
        End Get
        Set(value As List(Of Integer))
            judgeIdList = value
        End Set
    End Property

    Public Property FillIdList1 As List(Of Integer)
        Get
            Return fillIdList
        End Get
        Set(value As List(Of Integer))
            fillIdList = value
        End Set
    End Property

    Public Property Type1 As Integer
        Get
            Return type
        End Get
        Set(value As Integer)
            type = value
        End Set
    End Property

    Public Property SelectCount1 As Integer
        Get
            Return selectCount
        End Get
        Set(value As Integer)
            selectCount = value
        End Set
    End Property

    Public Property JudgeCount1 As Integer
        Get
            Return judgeCount
        End Get
        Set(value As Integer)
            judgeCount = value
        End Set
    End Property

    Public Property FillCount1 As Integer
        Get
            Return fillCount
        End Get
        Set(value As Integer)
            fillCount = value
        End Set
    End Property

    Public Property SelectScore1 As Integer
        Get
            Return selectScore
        End Get
        Set(value As Integer)
            selectScore = value
        End Set
    End Property

    Public Property JudgeScore1 As Integer
        Get
            Return judgeScore
        End Get
        Set(value As Integer)
            judgeScore = value
        End Set
    End Property

    Public Property FillScore1 As Integer
        Get
            Return fillScore
        End Get
        Set(value As Integer)
            fillScore = value
        End Set
    End Property

    Public Property ExamIdToUpdate As Integer
        Get
            Return examIdForUpdate
        End Get
        Set(value As Integer)
            examIdForUpdate = value
        End Set
    End Property

    ''' <summary>
    ''' 创建试卷，或者编辑试卷的load函数
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub CreateExam_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        '默认全部展开treeview的node
        'trQuestion.ExpandAll()
        cbSubType.SelectedIndex = 0
        '当examId不为零的时候，这个处于编辑状态，默认将所有数据都LOAD进来
        If examIdForUpdate <> 0 Then
            Me.Text = "修改试卷"
            btnSubmit.Text = "确定修改"
            Me.ExamTableAdapter1.FillById(Me.ExamDataSet.exam, examIdForUpdate)
            Me.View_exam_questionTableAdapter1.FillByExamId(Me.ExamDataSet.view_exam_question, examIdForUpdate)
            Dim row As ExamDataSet.examRow = Me.ExamDataSet.exam.Item(0)
            rtxExamName.Text = row.exam_name
            rtxExamtime.Text = row.exam_time.ToString()
            If row.is_active = 1 Then
                cbIsActive.Checked = True
            Else
                cbIsActive.Checked = False
            End If
            Dim veRow As ExamDataSet.view_exam_questionRow
            For Each veRow In Me.ExamDataSet.view_exam_question.Rows
                Dim exType As Integer = veRow.type
                Select Case exType
                    Case 0
                        If selectScore = 5 Then
                            selectScore = veRow.score
                            rtxSelectScore.Text = selectScore.ToString()
                            selectIdList.Add(veRow.question_id)

                        End If
                    Case 1
                        If judgeScore = 5 Then
                            judgeScore = veRow.score
                            rtxJudgeScore.Text = judgeScore.ToString()
                            judgeIdList.Add(veRow.question_id)
                        End If
                    Case 2
                        If fillScore = 5 Then
                            fillScore = veRow.score
                            rtxFillScore.Text = fillScore.ToString()
                            fillIdList.Add(veRow.question_id)
                        End If

                End Select
                idList.Add(veRow.question_id)
            Next
            refreshAll()
            type = 0
            'trQuestion.SelectedNode = trQuestion.Nodes("nodeSelect")
            updateDisplay()
        End If
    End Sub

    Private Sub TreeView1_NodeMouseClick(sender As Object, e As TreeNodeMouseClickEventArgs)
        'showQuestionList(e.Node.Name)
    End Sub

    ''' <summary>
    ''' 显示所有题目的列表
    ''' </summary>
    ''' <param name="selectIndex"></param>
    Private Sub showQuestionList(selectIndex As Integer)
        Dim sb As StringBuilder = buildIdsStr()
        Select Case selectIndex
            Case 0
                panelOptions.Visible = True
                type = 0
            Case 1
                panelOptions.Visible = False
                type = 1
            Case 2
                panelOptions.Visible = False
                type = 2

        End Select
        If Not String.IsNullOrEmpty(sb.ToString()) Then
            Select Case selectIndex
                Case 0
                    type = 0
                Case 1
                    type = 1
                Case 2
                    type = 2
            End Select
            refreshData()
        End If
        updateDisplay()

    End Sub

    ''' <summary>
    ''' 将id列表组合成，1,2,3,4,5 类型的字符串，方便在SQL查询时使用IN
    ''' </summary>
    ''' <returns></returns>
    Private Function buildIdsStr() As StringBuilder
        Dim sb As StringBuilder = New StringBuilder()
        For index = 0 To idList.Count - 1
            sb.Append(idList(index))
            If index <> idList.Count - 1 Then
                sb.Append(",")
            End If
        Next
        Return sb
    End Function

    Private Sub refreshAll()
        Me.QuestionTableAdapter.FillByIdsAndType(Me.QuestionDetailDataSet.question, 1, buildIdsStr().ToString())
        judgeCount = Me.QuestionDetailDataSet.question.Count
        lblJudgeNum.Text = judgeCount.ToString() + " 道"
        Threading.Thread.Sleep(50)
        Me.QuestionTableAdapter.FillByIdsAndType(Me.QuestionDetailDataSet.question, 2, buildIdsStr().ToString())
        fillCount = Me.QuestionDetailDataSet.question.Count
        lblFillNum.Text = fillCount.ToString() + " 道"
        Threading.Thread.Sleep(50)
        Me.QuestionTableAdapter.FillByIdsAndType(Me.QuestionDetailDataSet.question, 0, buildIdsStr().ToString())
        selectCount = Me.QuestionDetailDataSet.question.Count
        lblSelectNum.Text = selectCount.ToString() + " 道"
        Threading.Thread.Sleep(50)
        caculateTotalScore()
    End Sub

    Private Sub refreshData()
        Select Case type
            Case -1
            Case 0
                Me.QuestionTableAdapter.FillByIdsAndType(Me.QuestionDetailDataSet.question, type, buildIdsStr().ToString())
                selectCount = Me.QuestionDetailDataSet.question.Count
                lblSelectNum.Text = selectCount.ToString() + " 道"
            Case 1
                Me.QuestionTableAdapter.FillByIdsAndType(Me.QuestionDetailDataSet.question, type, buildIdsStr().ToString())
                judgeCount = Me.QuestionDetailDataSet.question.Count
                lblJudgeNum.Text = judgeCount.ToString() + " 道"
            Case 2
                Me.QuestionTableAdapter.FillByIdsAndType(Me.QuestionDetailDataSet.question, type, buildIdsStr().ToString())
                fillCount = Me.QuestionDetailDataSet.question.Count
                lblFillNum.Text = fillCount.ToString() + " 道"
        End Select
        caculateTotalScore()
    End Sub

    Private Sub caculateTotalScore()
        Dim totalScore As Integer = 0
        totalScore = selectCount * selectScore + judgeCount * judgeScore + fillCount * fillScore
        lblTotalScore.Text = totalScore.ToString()
    End Sub

    Private Sub btnAddSubject_Click(sender As Object, e As EventArgs) Handles btnAddSubject.Click
        Dim selQuestion As SelectQuestions = New SelectQuestions()
        selQuestion.ForSelect = True
        selQuestion.QueType = type
        selQuestion.ShowDialog()
        addNoDupList(idList, selQuestion.SelectedIds)
        Select Case type
            Case 0
                Dim newList As List(Of Integer) = addNoDupList(selectIdList, selQuestion.SelectedIds)
                addNoDupList(selectNewAddedIds, newList)
            Case 1
                Dim newList As List(Of Integer) = addNoDupList(judgeIdList, selQuestion.SelectedIds)
                addNoDupList(judgeNewAddedIds, newList)
            Case 2
                Dim newList As List(Of Integer) = addNoDupList(fillIdList, selQuestion.SelectedIds)
                addNoDupList(fillNewAddedIds, newList)
        End Select
        'showQuestionList(trQuestion.SelectedNode.Name)
        showQuestionList(cbSubType.SelectedIndex)

    End Sub

    Private Function addNoDupList(destList As List(Of Integer), toAddList As List(Of Integer)) As List(Of Integer)
        Dim newList As New List(Of Integer)
        Dim i As Integer
        For Each i In toAddList
            If Not destList.Contains(i) Then
                destList.Add(i)
                newList.Add(i)
            End If
        Next
        Return newList
    End Function

    Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
        Dim exam_name As String = rtxExamName.Text
        Dim exam_time As Integer = Integer.Parse(rtxExamtime.Text)
        Dim is_active As Integer = 0
        If cbIsActive.Checked Then
            is_active = 1
        End If
        Try
            If examIdForUpdate <> 0 Then
                Me.ExamTableAdapter1.UpdateByExamId(exam_name, exam_time, is_active, ExamGlobal.LOGIN_NAME, Date.Now(), examIdForUpdate)
                updateExamScore(examIdForUpdate, selectIdList, selectScore)
                updateExamScore(examIdForUpdate, judgeIdList, judgeScore)
                updateExamScore(examIdForUpdate, fillIdList, fillScore)
                saveToExamQuesions(examIdForUpdate, selectNewAddedIds, selectScore)
                saveToExamQuesions(examIdForUpdate, judgeNewAddedIds, judgeScore)
                saveToExamQuesions(examIdForUpdate, fillNewAddedIds, fillScore)
                deleteQuestionFromExam(examIdForUpdate, toDeleteIds)
                Me.Stu_examTableAdapter1.UpdateByExamId(exam_name, is_active, Date.Now(), examIdForUpdate)
                MessageBox.Show("修改试卷成功")
            Else
                Dim exam_id As Integer = Me.ExamTableAdapter1.InsertExam(exam_name, exam_time, is_active, ExamGlobal.LOGIN_NAME, Date.Now(), Date.Now())
                saveToExamQuesions(exam_id, selectIdList, selectScore)
                saveToExamQuesions(exam_id, judgeIdList, judgeScore)
                saveToExamQuesions(exam_id, fillIdList, fillScore)
                Me.Stu_examTableAdapter1.InsertAllStuId()
                Me.Stu_examTableAdapter1.UpdateEmptyExam(exam_id, exam_name, "N", is_active.ToString(), Date.Now(), Date.Now())
                MessageBox.Show("创建试卷成功")
            End If
            Me.Close()
        Catch ex As Exception
            MessageBox.Show("提交失败，原因：" + ex.Message)
        End Try
    End Sub

    Private Sub deleteQuestionFromExam(examId As Integer, ids As List(Of Integer))
        For index = 0 To ids.Count - 1
            Me.Exam_questionsTableAdapter1.DeleteByExamIdANDqueId(examId, ids(index))
        Next
    End Sub

    Private Sub updateExamScore(examId As Integer, ids As List(Of Integer), score As Integer)
        For index = 0 To ids.Count - 1
            Me.Exam_questionsTableAdapter1.UpdateScore(score, examId, ids(index))
        Next
    End Sub

    Private Sub saveToExamQuesions(examId As Integer, ids As List(Of Integer), score As Integer)
        For index = 0 To ids.Count - 1
            Me.Exam_questionsTableAdapter1.InsertExamQuesion(examId, ids(index), score)
        Next
    End Sub

    Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
        idList.Remove(lbChoosen.SelectedValue)
        toDeleteIds.Add(lbChoosen.SelectedValue)
        refreshData()
    End Sub

    Private Sub rtxSelectScore_TextChanged(sender As Object, e As EventArgs) Handles rtxSelectScore.TextChanged
        Try
            selectScore = Integer.Parse(rtxSelectScore.Text)
            caculateTotalScore()
            lblScoreValidate.Text = ""
        Catch ex As Exception
            lblScoreValidate.Text = "必须填入数字"
        End Try
    End Sub

    Private Sub rtxJudgeScore_TextChanged(sender As Object, e As EventArgs) Handles rtxJudgeScore.TextChanged
        Try
            judgeScore = Integer.Parse(rtxJudgeScore.Text)
            caculateTotalScore()
            lblJudgeVali.Text = ""
        Catch ex As Exception
            lblJudgeVali.Text = "必须填入数字"
        End Try
    End Sub

    Private Sub rtxFillScore_TextChanged(sender As Object, e As EventArgs) Handles rtxFillScore.TextChanged
        Try
            fillScore = Integer.Parse(rtxFillScore.Text)
            caculateTotalScore()
            lblFillVali.Text = ""
        Catch ex As Exception
            lblFillVali.Text = "必须填入数字"
        End Try
    End Sub

    Private Sub txtAnswer_TextChanged(sender As Object, e As EventArgs) Handles txtAnswer.TextChanged
        updateDisplay()
    End Sub

    Private Sub txtOptions_TextChanged(sender As Object, e As EventArgs) Handles txtOptions.TextChanged
        If txtOptions.Text.Contains("||") Then
            txtOptionDisplay.Text = ""
            updateOptions()
        End If
    End Sub

    Private Sub lbChoosen_Click(sender As Object, e As EventArgs) Handles lbChoosen.Click
        'updateDisplay()
    End Sub

    Private Sub clearDisplay()
        txtOptionDisplay.Text = ""
        txtDisplayAnswer.Text = ""
    End Sub

    Private Sub updateDisplay()
        clearDisplay()
        Select Case type
            Case 0
                txtDisplayAnswer.Text = txtAnswer.Text
                updateOptions()
            Case 1
                If txtAnswer.Text.Equals("0") Then
                    txtDisplayAnswer.Text = "错误"
                ElseIf txtAnswer.Text.Equals("1") Then
                    txtDisplayAnswer.Text = "正确"
                Else
                    txtDisplayAnswer.Text = ""
                End If
            Case 2
                Dim answers() As String = txtAnswer.Text.Split(ExamGlobal.Spliter, StringSplitOptions.RemoveEmptyEntries)
                Dim str As String
                For Each str In answers
                    txtDisplayAnswer.Text += str
                    txtDisplayAnswer.Text += System.Environment.NewLine
                Next
        End Select
    End Sub

    Private Sub updateOptions()
        If txtOptions.Text.Contains("||") Then
            Dim options() As String = txtOptions.Text.Split(ExamGlobal.Spliter, StringSplitOptions.RemoveEmptyEntries)
            If options.Count = 4 Then
                txtOptionDisplay.Text += "A：" + options(0)
                txtOptionDisplay.Text += System.Environment.NewLine
                txtOptionDisplay.Text += "B：" + options(1)
                txtOptionDisplay.Text += System.Environment.NewLine
                txtOptionDisplay.Text += "C：" + options(2)
                txtOptionDisplay.Text += System.Environment.NewLine
                txtOptionDisplay.Text += "D：" + options(3)

            End If

        End If
    End Sub

    Private Sub cbSubType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbSubType.SelectedIndexChanged
        showQuestionList(cbSubType.SelectedIndex)
    End Sub
End Class